<template>
  <div>
    <div style="display: flex;justify-content: space-between">
      <el-form :inline="true">
        <el-form-item>
          <div v-if="sensorList.length > 1">
            <div v-if="sensorList.length < 4">
              <el-checkbox-group v-model="choseSensorIdList" @change="formatDeviceSettingList">
                <el-checkbox
                  v-for="item in sensorList"
                  :key="item.sensorId"
                  :label="item.sensorId"
                >
                  <span>{{ item.sensorName || $t('port') + item.port }}</span>
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <el-select
              v-else
              v-model="choseSensorIdList"
              multiple
              style="width: 600px"
              @change="formatDeviceSettingList"
            >
              <el-option
                v-for="item in sensorList"
                :key="item.sensorId"
                :label="item.sensorName || $t('port')+':'+item.port"
                :value="item.sensorId"
              >
                <span style="color: #8492a6;font-size: 13px">[{{ $t('port') + item.port }}]</span>
                <span>{{ item.sensorName }}</span>
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="name"
            clearable
            :placeholder="$t('name')"
            @change="listSensorWith"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="listSensorWith"
          >{{ $t('search') }}
          </el-button>
        </el-form-item>
      </el-form>
      <div style="width: 120px">
        <el-switch
          v-model="qrCodeModel"
          style="margin-top: 5px"
          :active-text="$t('qrCode')"
        />
      </div>
    </div>
    <div v-if="videoOptions">
      <div class="flex justify-end mb-1 ">
        <el-button type="danger" icon="el-icon-circle-close" @click="videoOptions = null">{{ $t('close') }}</el-button>
      </div>
      <video-player
        height="280px"
        width="100%"
        :options="videoOptions"
      />
    </div>
    <el-alert
      v-if="settingLoading"
      :title="$t('loading')"
      type="warning"
      center
      show-icon
      :closable="false"
    />
    <div
      v-for="(sensor,sensorIndex) in showSensorList"
      v-else
      :key="sensorIndex"
    >
      <div v-if="sensor.editSensor == true" style="margin-top: 5px">
        <el-input v-model="sensor.name" style="width: 300px">
          <el-button
            slot="append"
            icon="el-icon-check"
            @click.stop="updateSensorName(sensor)"
          />
          <el-button
            slot="append"
            icon="el-icon-close"
            @click.stop="cancelUpdateSensorName(sensor)"
          />
        </el-input>
      </div>
      <div
        v-else
        class="text-gray-400"
        style="line-height: 40px;font-size:15px;margin-left: 13px"
        @click="editSensor(sensor)"
      >
        <span class="primary-color">{{ formatSensorType(sensor.type) }}{{ $t('port') }}:{{ sensor.port }}</span>
        <span style="margin-left: 3px;">{{ sensor.name }}</span>
      </div>
      <div
        v-for="(item,index) in sensor.settingList"
        :key="index"
      >
        <div
          v-if="showHidden === '1' || !item.hidden"
          class="flex justify-between content-center item"
          style="padding: 12px"
        >
          <div class="flex" style="width: calc(100% - 500px)">
            <el-image
              style="width:30px;height:30px;margin-right: 8px;"
              :src="item.iconUrl"
            />
            <div>
              <div class="text-xs">
                <el-popover
                  v-if="item.remark && item.remark!==''"
                  placement="top"
                  width="200"
                  trigger="hover"
                  :content="item.name"
                >
                  <span slot="reference">{{ item.remark }}</span>
                </el-popover>
                <span v-else>
                  <span>{{ item.name }}</span>
                </span>
              </div>
              <div class="text-xs">{{ formatDate(item.updateDate) }}</div>
            </div>
          </div>
          <div style="width: 580px">
            <div v-if="item.type === 'fixedParam'">
              <div v-if="item.paramList.length > 5">
                <el-select
                  v-model="item.value"
                  style="width: 300px"
                  filterable
                  :disabled="item.disabled"
                >
                  <el-option
                    v-for="item2 in item.paramList"
                    :key="item2.value"
                    :label="item2.name + item.unit"
                    :value="item2.value"
                  />
                </el-select>
                <el-button
                  type="primary"
                  :disabled="item.disabled"
                  @click.stop="valueChange(item)"
                >{{ $t('confirm') }}
                </el-button>
              </div>
              <el-button
                v-for="(item2,index2) in item.paramList"
                v-else
                :key="index2"
                type="primary"
                :plain="item2.value !== item.value"
                :disabled="item2.disabled"
                @click="valueChange(item2)"
              >{{ item2.name + item.unit }}
              </el-button>
            </div>
            <div v-else-if="item.type === 'switch'">
              <el-switch
                v-model="item.value"
                :disabled="item.disabled"
                :active-text="$t('open')"
                :inactive-text="$t('close')"
                active-value="1"
                inactive-value="0"
                @change="valueChange(item)"
              />
            </div>
            <div v-else-if="item.type === 'time'">
              <el-time-picker
                v-model="item.value"
                :disabled="item.disabled"
                style="width:300px"
                value-format="HH:mm"
                format="HH:mm"
                :placeholder="$t('timing')"
              />
              <el-button
                type="primary"
                :disabled="item.disabled"
                @click.stop="valueChange(item)"
              >{{ $t('confirm') }}
              </el-button>
            </div>
            <div v-else-if="item.type === 'timeSlot'" class="flex">
              <time-slot v-model="item.value" :disabled="item.disabled"/>
              <el-button
                type="primary"
                :disabled="item.disabled"
                @click.stop="valueChange(item)"
              >{{ $t('confirm') }}
              </el-button>
            </div>
            <div v-else-if="item.type === 'noParam'">
              <el-button
                type="primary"
                :disabled="item.disabled"
                @click.stop="valueChange(item)"
              >{{ $t('confirm') }}
              </el-button>
            </div>
            <div v-else-if="item.type === 'slider'">
              <el-slider
                v-model="item.value"
                style="width:360px"
                :disabled="item.disabled"
                @change="valueChange(item)"
              />
            </div>
            <div v-else-if="item.type === 'video'">
              <el-input
                v-model="item.value"
                style="width:300px"
                :disabled="item.disabled"
              >
                <template v-if="item.unit" slot="append">{{ item.unit }}</template>
              </el-input>
              <el-button
                type="primary"
                :disabled="item.disabled"
                @click.stop="valueChange(item)"
              >{{ $t('play') }}
              </el-button>
            </div>
            <div v-else-if="item.type === 'multiCustom'" class="flex flex-wrap items-center">
              <div
                v-for="(param,paramIndex) in item.valueList"
                :key="paramIndex"
                style="margin:0 5px 5px 5px"
              >
                <div v-if="param.type === 'switch'">
                  <el-switch
                    v-model="param.value"
                    active-value="1"
                    inactive-value="0"
                    :disabled="item.disabled"
                  />
                </div>
                <div v-else-if="param.type === 'time'">
                  <el-time-picker
                    v-model="param.value"
                    :disabled="item.disabled"
                    style="width:100px"
                    value-format="HH:mm"
                    format="HH:mm"
                    :placeholder="$t('timing')"
                  />
                </div>
                <div v-else-if="param.type === 'timeSlot'">
                  <time-slot v-model="param.value" :disabled="item.disabled"/>
                </div>
                <div v-else-if="param.type === 'slider'">
                  <el-slider
                    v-model="param.value"
                    input-size="mini"
                    :disabled="item.disabled"
                    style="width:200px;"
                  />
                </div>
                <div v-else-if="param.type === 'fixedParam'">
                  <el-select
                    v-model="param.value"
                    style="width:100px"
                    :disabled="item.disabled"
                    filterable
                  >
                    <el-option
                      v-for="item2 in item.paramList"
                      :key="item2.value"
                      :label="item2.name + item.unit"
                      :value="item2.value"
                    />
                  </el-select>
                </div>
                <el-input
                  v-else
                  v-model="param.value"
                  style="width:55px"
                  :disabled="item.disabled"
                >
                  <template v-if="item.unit" slot="append">{{ item.unit }}</template>
                </el-input>
              </div>
              <el-button
                style="margin:0 5px 5px 5px"
                type="primary"
                :disabled="item.disabled"
                @click.stop="valueChange(item)"
              >{{ $t('confirm') }}
              </el-button>
            </div>
            <div v-else="">
              <el-input
                v-model="item.value"
                style="width:300px"
                :disabled="item.disabled"
              >
                <template v-if="item.unit" slot="append">{{ item.unit }}</template>
              </el-input>
              <el-button
                type="primary"
                :disabled="item.disabled"
                @click.stop="valueChange(item)"
              >{{ $t('confirm') }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      append-to-body
      destroy-on-close
      :label="$t('qrCode')"
      :visible.sync="showQrCode"
      width="340px"
    >
      <div
        ref="qrcode"
        style="width: 100%;height: 100%"
      />
    </el-dialog>
  </div>
</template>

<script>
import { formatDate, formatDeviceSetting, formatSensorType, successMessage, successNotice } from '@/util/common'
import { sendDeviceSetting } from '@/api/iot/iotDeviceSettingApi'
import { listSensorWith, updateSensor } from '@/api/iot/iotDeviceSensorApi'
import { getQrCodeBaseUrl, getShowHidden, getShowSensorAuto } from '@/util/storage'
import QRCode from 'qrcodejs2'
import { leaveWebSocket, listenWebSocket } from '@/util/websocketTool'
import TimeSlot from '@/components/TimeSlot'
import VideoPlayer from '@/components/VideoPlayer'

export default {
  name: 'DeviceSetting',
  components: {
    TimeSlot,
    VideoPlayer
  },
  props: {
    deviceCore: {
      type: String,
      default: null
    },
    sensorId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      name: null,
      choseSensorIdList: [],
      sensorList: [],
      showSensorList: [],
      setting: null,
      settingLoading: false,
      qrCodeModel: false,
      showQrCode: false,
      lastDeviceCore: null,
      videoOptions: null,
      showHidden: getShowHidden(),
      showSensorAuto: getShowSensorAuto(),
      wsMonitor: {
        room: 'iot:device:' + this.deviceCore,
        onmessage: this.onSocketMsg
      }
    }
  },
  watch: {
    deviceCore: {
      deep: true,
      handler(val) {
        if (this.deviceCore) {
          if (this.lastDeviceCore != null) {
            leaveWebSocket(this.wsMonitor)
          }
          this.wsMonitor.room = 'iot:device:' + this.deviceCore
          listenWebSocket(this.wsMonitor)
          this.lastDeviceCore = this.deviceCore
        }
        this.init()
      }
    },
    sensorId: {
      deep: true,
      handler(val) {
        this.init()
      }
    }
  },
  created() {
    this.init()
  },
  beforeDestroy() {
    this.closeSocket()
  },
  methods: {
    init() {
      this.choseSensorIdList = []
      this.listSensorWith()
      this.wsMonitor.room = 'iot:device:' + this.deviceCore
      listenWebSocket(this.wsMonitor)
    },
    closeSocket() {
      leaveWebSocket(this.wsMonitor)
    },
    onSocketMsg(nowData) {
      if (nowData.type === 'deviceData') {
        const data = JSON.parse(nowData.msg)
        if (data.deviceUpload) {
          if (data.deviceUpload.setting) {
            this.sensorList.forEach(deviceSensor => {
              if (deviceSensor.settingList && deviceSensor.settingList.length > 0) {
                for (let i = 0, j = deviceSensor.settingList.length; i < j; i++) {
                  const setting = deviceSensor.settingList[i]
                  if (data.deviceUpload.setting.keyName === setting.keyName && data.deviceUpload.setting.port === setting.port) {
                    if (data.deviceUpload.setting.value !== undefined) {
                      setting.value = data.deviceUpload.setting.value
                    }
                    setting.updateDate = nowData.timestamp
                    deviceSensor.settingList.splice(i, 1, setting)
                  }
                }
              }
            })
            this.formatDeviceSettingList()
          }
          if (data.deviceUpload.sensorList && data.deviceUpload.sensorList.length > 0) {
            data.deviceUpload.sensorList.forEach(sensor => {
              this.sensorList.forEach(deviceSensor => {
                if (sensor.port === deviceSensor.port) {
                  if (sensor.settingList && sensor.settingList.length > 0 && deviceSensor.settingList && deviceSensor.settingList.length > 0) {
                    sensor.settingList.forEach(item => {
                      for (let i = 0, j = deviceSensor.settingList.length; i < j; i++) {
                        const setting = deviceSensor.settingList[i]
                        if (item.keyName === setting.keyName) {
                          setting.value = item.value
                          setting.updateDate = nowData.timestamp
                          deviceSensor.settingList.splice(i, 1, setting)
                        }
                      }
                    })
                    this.formatDeviceSettingList()
                  }
                }
              })
            })
          }
        }
      }
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    cancelUpdateSensorName(item) {
      for (const i in this.showSensorList) {
        if (this.showSensorList[i].sensorId === item.sensorId) {
          item.editSensor = false
          this.showSensorList.splice(i, 1, item)
        }
      }
    },
    updateSensorName(item) {
      updateSensor({
        sensorId: item.sensorId,
        sensorName: item.sensorName
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        for (const i in this.showSensorList) {
          if (this.showSensorList[i].sensorId === item.sensorId) {
            item.editSensor = false
            this.showSensorList.splice(i, 1, item)
          }
        }
      })
    },
    editSensor(item) {
      for (const i in this.showSensorList) {
        if (this.showSensorList[i].sensorId === item.sensorId) {
          item.editSensor = true
          this.showSensorList.splice(i, 1, item)
        }
      }
    },
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    fStatus(item) {
      if (item.status > 1) {
        return this.$t('failure')
      } else if (item.status === 0) {
        return this.$t('unKnow')
      } else {
        return this.$t('success')
      }
    },
    valueChange(item) {
      this.setting = item
      if (this.setting.type === 'multiCustom') {
        let value = ''
        this.setting.valueList.forEach(v => {
          if (value === '') {
            value = v.value
          } else {
            value = value + ',' + v.value
          }
        })
        this.setting.value = value
      }
      this.updateVal()
    },
    listSensorWith() {
      this.settingLoading = true
      this.sensorList = []
      const json = {
        deviceCore: this.deviceCore,
        sensorId: this.sensorId,
        withSetting: true
      }
      listSensorWith(json).then(res => {
        const { code, data } = res
        const sensorList = []
        if (code === '200') {
          for (let i = 0, j = data.length; i < j; i++) {
            const sensor = data[i]
            if (this.showHidden !== '1' && sensor.hidden) {
              continue
            }
            if (this.showSensorAuto === '1' && (!sensor.settingList || sensor.settingList.length === 0)) {
              continue
            }
            sensorList.push(sensor)

            if (this.choseSensorIdList.length > i) {
              continue
            } else if (this.sensorId) {
              this.choseSensorIdList = [this.sensorId]
            } else {
              this.choseSensorIdList.push(sensor.sensorId)
            }
          }
        }
        this.sensorList = sensorList
        this.formatDeviceSettingList()
        this.settingLoading = false
      })
    },
    formatDeviceSettingList() {
      const showSensorList = []
      for (let n = 0, m = this.sensorList.length; n < m; n++) {
        const sensor = this.sensorList[n]
        if (!this.choseSensorIdList || !this.choseSensorIdList.includes(sensor.sensorId)) {
          continue
        }
        const settingList = []
        for (let i = 0, j = sensor.settingList.length; i < j; i++) {
          let setting = {
            ...sensor.settingList[i]
          }
          if (this.name) {
            if (setting.name.indexOf(this.name) < 0) {
              continue
            }
          }
          setting = formatDeviceSetting(setting)
          settingList.push(setting)
        }
        if (!sensor.settingList || sensor.settingList.length === 0) {
          continue
        }
        showSensorList.push({
          sensorId: sensor.sensorId,
          name: sensor.sensorName,
          port: sensor.port,
          type: sensor.type,
          status: sensor.status,
          settingList: settingList
        })
      }
      this.showSensorList = showSensorList
    },
    updateVal() {
      if (this.qrCodeModel) {
        this.showQrCode = true
        this.$nextTick(() => {
          const url = getQrCodeBaseUrl() + '?deviceCore=' + this.deviceCore + '&function=setting&keyName=' + this.setting.keyName + '&value=' + this.setting.value + '&port=' + this.setting.port + '&name=' + this.setting.name
          new QRCode(this.$refs.qrcode, {
            text: url,
            width: 300,
            height: 300,
            colorDark: '#333333', // 二维码颜色
            colorLight: '#ffffff', // 二维码背景色
            correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
          })
        })
      } else {
        this.settingLoading = true
        const json = {
          tag: 'manage',
          settingId: this.setting.settingId,
          keyName: this.setting.keyName,
          value: this.setting.value,
          port: this.setting.port,
          deviceCore: this.deviceCore
        }
        sendDeviceSetting(json).then(res => {
          const { code, data } = res
          if (code === '200') {
            successMessage(this)
            if (this.setting.type === 'video') {
              this.videoOptions = {
                autoplay: true,
                controls: true,
                sources: [{
                  src: data.setting.value,
                  type: 'application/x-mpegURL'
                }]
              }
            }
          }
          this.listSensorWith()
        })
      }
    }
  }

}
</script>
<style scoped lang="scss">
@import '@/styles/element-variables.scss';

.primary-color {
  color: $--color-primary;
}

.item:hover {
  background-color: #ebeef5;
  border-radius: 14px;
}
</style>

